<?php
/**
 * Created by PhpStorm.
 * User: 沁塵
 * Date: 2019/4/20
 * Time: 19:57
 */

namespace app\api\controller\v1;

use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use app\api\model\Upload as UploadModel;
use app\api\model\ModelEvent;
use app\api\model\SdModelEvent;
use think\Request;

class Upload
{
    /**
     * 销豹 同步改写结果
     * @param Request $request
     * @return \think\response\Json
     */
    public function xbNotify(Request $request)
    {
        $params = $request->post();
        $task_id = $params['task_id']??$params["scene_task_id"];
        $params["back_time"] = date('Y-m-d H:i:s');
        \app\api\model\Upload::where('task_id',$task_id)->update($params);

//        回填人设主任务
        if (isset($params["fail_reason"])) {
            $info = \app\api\model\Upload::where("task_id", $task_id)->findOrEmpty();
            if (!empty($info["main_task_id"])) {
                if ($info["platform"] == "逛逛三版") {
                    \app\api\model\ModelEvent::where("main_task_id", $info["main_task_id"])->update([
                        "status"=>24,
                        "reason"=>$params["fail_reason"]
                    ]);
                } elseif ($info["platform"] == "逛逛四版") {
                    \app\api\model\SdModelEvent::where("main_task_id", $info["main_task_id"])->update([
                        "status"=>24,
                        "reason"=>$params["fail_reason"]
                    ]);
                }
            }
        }

        return writeJson(201, '', '回调修改成功');
    }


    public function createUpload(Request $request) {
        $params = $request->post();
        $params = json_decode($params['data'], true);
        foreach ($params as $v) {
            $data = [
                'sound_model' => $v['sound_model'], //声音模型
                'video_text' => $v['video_text'], //视频文案
                'product_video_url' => $v['product_video_url'], //视频链接
                'product_id' => $v['product_id'], //商品id
                'get_status' => 1,
                'platform' => $v['platform'], //平台名字 淘宝 拼多多
                'create_time' => date('Y-m-d H:i:s')
            ];
            UploadModel::insert($data);
        }
        return writeJson(200, '', '提交成功');
    }

    public function getUpload() {
        $upload = UploadModel::where('get_status','1')->where("is_top", 1)->findOrEmpty();
        if ($upload->isEmpty()) {
            $upload = UploadModel::where('get_status','1')->findOrEmpty();
        }
        if (!$upload->isEmpty()) {
            UploadModel::where('id',$upload['id'])->update(['get_status'=>'2']);
            return writeJson(200, $upload, '请求成功');
        } else {
            return writeJson(200, null, '暂无');
        }

    }

    public function getUploadFail(Request $request) {
        $params = $request->get();

        $upload = UploadModel::where('get_status',$params["get_status"])
            ->whereNull("task_id")
            ->whereNull("qiniu")
            ->find();
        UploadModel::where('id',$upload['id'])->update(['get_status'=>'2']);
        return writeJson(200, $upload, '请求成功');
    }


    public function updateUpload(Request $request) {
        $params = $request->post();
        UploadModel::where('id',$params['id'])->update($params);
        return writeJson(200, '', '请求成功');
    }

    public function getQiniuToken($this_bucket=null){
        // 配置信息
        $accessKey = 'Fxo_ez_SxoLppSGB_p6WViS9xTc6ii62YR66zBVZ';
        $secretKey = 'nXShYVprxVq9N_VzAM5vFwRb8vgpQevW0FoueyZI';
        $bucket = $this_bucket??'yseh';
        $auth = new Auth($accessKey, $secretKey);
        $upToken = $auth->uploadToken($bucket);
        return writeJson(200, $upToken, '请求成功');

    }

    public function getQiniuBucketToken(Request $request){
        $params = $request->get();
        // 配置信息
        $accessKey = 'Fxo_ez_SxoLppSGB_p6WViS9xTc6ii62YR66zBVZ';
        $secretKey = 'nXShYVprxVq9N_VzAM5vFwRb8vgpQevW0FoueyZI';
        $bucket = $params['bucket']??'yseh';
        $auth = new Auth($accessKey, $secretKey);
        $upToken = $auth->uploadToken($bucket);
        return writeJson(200, $upToken, '请求成功');

    }

    public function uploadVideo()
    {
        set_time_limit(0);
        ini_set('memory_limit', '256M');
        ini_set('max_execution_time', 1000);
        ini_set('max_input_time', 1000);
        // 配置信息
        $accessKey = 'Fxo_ez_SxoLppSGB_p6WViS9xTc6ii62YR66zBVZ';
        $secretKey = 'nXShYVprxVq9N_VzAM5vFwRb8vgpQevW0FoueyZI';
        $bucket = 'yseh';
        $auth = new Auth($accessKey, $secretKey);
        $upToken = $auth->uploadToken($bucket);

        // 上传管理类
        $uploadMgr = new UploadManager();

        // 获取上传文件
        $file = request()->file('file');

        $chunkSize = 6 * 1024 * 1024;

        $filename = time().'_'.rand(10000,99999).'.mp4';
        $url = 'https://www.youdnr.cn/'.$filename;
        // 上传到七牛
        list($ret, $err) = $uploadMgr->putFile($upToken, $filename, $file->getPathname(),null,$chunkSize);

        if ($err !== null) {
            return writeJson(200, $err, '上传失败');
        } else {
            return writeJson(200, $url, '请求成功');
        }
    }

    public function uploadPic()
    {
        // 配置信息
        $accessKey = 'Fxo_ez_SxoLppSGB_p6WViS9xTc6ii62YR66zBVZ';
        $secretKey = 'nXShYVprxVq9N_VzAM5vFwRb8vgpQevW0FoueyZI';
        $bucket = 'yseh';
        $auth = new Auth($accessKey, $secretKey);
        $upToken = $auth->uploadToken($bucket);

        // 上传管理类
        $uploadMgr = new UploadManager();

        // 获取上传文件
        $file = request()->file('file');

        $filename = time().'_'.rand(10000,99999).'.png';
        $url = 'https://www.youdnr.cn/'.$filename;
        // 上传到七牛
        list($ret, $err) = $uploadMgr->putFile($upToken, $filename, $file->getPathname());

        if ($err !== null) {
            return writeJson(200, $err, '上传失败');
        } else {
            return json_encode(['code'=>0,'msg'=>'','data'=> ['src'=>$url]]);
        }

    }

    public function list(Request $request)
    {
        $params = $request->post();

        $pageSize = $params['pageSize'] ?? 50;
        $upload = new \app\api\model\Upload();


        if (!empty($params["model"])) {
            $upload = $upload->where("model", $params["model"]);
        }
        if (!empty($params["status"])) {
            $upload = $upload->where("status", $params["status"]);
        }
        if (!empty($params["start_time"])) {
            $upload = $upload->where("create_time", ">", $params["start_time"]);
        }
        $list = $upload->whereIn("platform", ['逛逛三版', '逛逛四版'])->paginate($pageSize);
        return writeJson(200,$list,'数据列表！');

    }

    public function getQiniuNull(Request $request)
    {
        $params = $request->get();

        $upload = \app\api\model\Upload::whereNull("qiniu")
            ->where("platform", $params["platform"])
            ->where("status", 1)
            ->where(function ($q){
                $ten_min_ago = date("Y-m-d H:i:s", time() - 300);
                $q->whereNull('back_time')->whereOr('back_time','<',$ten_min_ago);
            })->limit(5)->select()->toArray();

        return writeJson(200,$upload,'数据列表！');

    }

    public function addUpload(Request $request) {
        $params = $request->post();
        UploadModel::create($params);
        return writeJson(200, '', '请求成功');
    }

    public function checkByMainTaskId(Request $request) {
        $params = $request->post();
        $event = new UploadModel();
        $platform = $params["platform"]??"逛逛六版";
        $count = $event->where("main_task_id", $params["main_task_id"])
            ->where("platform", $platform)
            ->where("product_id", $params["product_id"])
            ->where("number", $params["number"])
            ->count();
        if ($count == 0) {
            return writeJson(200, false, '请求成功');
        } else {
            return writeJson(200, true, '请求成功');
        }

    }

    public function check(Request $request) {
        $params = $request->post();
        $event = new UploadModel();
        $count = $event->where("model", $params["model"])
            ->where("product_id", $params["product_id"])
            ->where("filename", $params["filename"])
            ->count();
        if ($count == 0) {
            return writeJson(200, false, '请求成功');
        } else {
            return writeJson(200, true, '请求成功');
        }

    }

    public function syncList(Request $request)
    {
        $params = $request->post();
        $ids = json_decode($params["ids"], true);
        $event = new UploadModel();

        $all = $event->where("model", $params["model"])
            ->where("platform", "逛逛")
            ->where("status", 1)
            ->select()->toArray();

    }

    public function findUpload(Request $request)
    {
        $params = $request->post();
        $info = UploadModel::field("model,filename,product_id,product_name")->where("qiniu", $params["qiniu"])->findOrEmpty();
        return writeJson(200, $info, '请求成功');
    }

    public function randomGet(Request $request)
    {
        $params = $request->post();
        $info = UploadModel::where("model", $params["model"])
            ->where("product_id", $params["product_id"])
            ->whereNotNull("qiniu")
            ->whereNull("in_use")
            ->orderRand()->findOrEmpty();
        return writeJson(200, $info, '请求成功');
    }


    public function backSyncTask(Request $request)
    {
        $params = $request->post();
        $upload = UploadModel::where("id", $params["id"])->find();
        $upload->video_url = $params['video_url'];
        $upload->get_status = $params['get_status'];
        $upload->reason = $params['reason'];
        if (!empty($params["video_url"])) {
            $upload->status = 1;
            if (strpos($params["video_url"], "youdnr") !== false) {
                $upload->qiniu = $params['video_url'];
            }
        }
        $upload->save();

        return writeJson(200, $upload, '请求成功');
    }


    public function resetUpload()
    {
        $res2 = UploadModel::where("platform", "逛逛六版")->where("get_status", 4)->whereNull("qiniu")
            ->whereLike("reason", "The upstream Gradio app has raised an exception%")->update(["get_status"=>5]);

        $res1 = UploadModel::where("platform", "逛逛六版")->where("get_status", 4)->whereNull("qiniu")
            ->update(["get_status"=>1]);

//        $res3 = UploadModel::where("platform", "逛逛六版")->where("get_status", 4)->whereNull("qiniu")
//            ->where("type", ">", 1)->update(["get_status"=>5]);

        return writeJson(200,"重置本地口型失败：{$res1}，重置多人脸：{$res2}",'成功！');

    }

}